{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnx\n",
    "from onnx import helper, shape_inference\n",
    "from onnx import TensorProto\n",
    "import onnx.optimizer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Building a FC model for MNIST"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import numpy as np\n",
    "import scipy.stats as stats\n",
    "\n",
    "def truncated_normal(dims):   \n",
    "    size = 1\n",
    "    for dim in dims:\n",
    "        size *= dim\n",
    "\n",
    "    mu, stddev = 0, 1/math.sqrt(size)\n",
    "    lower, upper = -2 * stddev, 2 * stddev\n",
    "    X = stats.truncnorm( (lower - mu) / stddev, (upper - mu) / stddev, loc = mu, scale = stddev)\n",
    "\n",
    "    return X.rvs(size).tolist()\n",
    "\n",
    "    \n",
    "def zeros(dim):\n",
    "    return [0] * dim[0]\n",
    "   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = -1\n",
    "\n",
    "W1_dims = [8, 1, 5, 5]\n",
    "W2_dims = [16, 8, 5, 5]\n",
    "W3_dims = [256, 10]\n",
    "\n",
    "W1 =  helper.make_tensor(name=\"W1\", data_type=onnx.TensorProto.FLOAT, dims=W1_dims, vals=truncated_normal(W1_dims))\n",
    "W2 =  helper.make_tensor(name=\"W2\", data_type=onnx.TensorProto.FLOAT, dims=W2_dims, vals=truncated_normal(W2_dims))\n",
    "W3 =  helper.make_tensor(name=\"W3\", data_type=onnx.TensorProto.FLOAT, dims=W3_dims, vals=truncated_normal(W3_dims))\n",
    "\n",
    "B1_dims = [8]\n",
    "B2_dims = [16]\n",
    "B3_dims = [10]\n",
    "\n",
    "B1 =  helper.make_tensor(name=\"B1\", data_type=onnx.TensorProto.FLOAT, dims=B1_dims, vals=zeros(B1_dims))\n",
    "B2 =  helper.make_tensor(name=\"B2\", data_type=onnx.TensorProto.FLOAT, dims=B2_dims, vals=zeros(B2_dims))\n",
    "B3 =  helper.make_tensor(name=\"B3\", data_type=onnx.TensorProto.FLOAT, dims=B3_dims, vals=zeros(B3_dims))\n",
    "\n",
    "\n",
    "shape = helper.make_tensor(name=\"shape\", data_type=onnx.TensorProto.INT64, dims=[2], vals=[batch_size, 256])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "node1 = helper.make_node('Conv', inputs=['X', 'W1', 'B1'], outputs=['T1'], kernel_shape=[5,5], strides=[1,1], pads=[2,2,2,2])\n",
    "node2 = helper.make_node('Relu', inputs=['T1'], outputs=['T2'])\n",
    "node3 = helper.make_node('MaxPool', inputs=['T2'], outputs=['T3'], kernel_shape=[2,2], strides=[2,2])\n",
    "\n",
    "node4 = helper.make_node('Conv', inputs=['T3', 'W2', 'B2'], outputs=['T4'], kernel_shape=[5,5], strides=[1,1], pads=[2,2,2,2])\n",
    "node5 = helper.make_node('Relu', inputs=['T4'], outputs=['T5'])\n",
    "node6 = helper.make_node('MaxPool', inputs=['T5'], outputs=['T6'], kernel_shape=[3,3], strides=[3,3])\n",
    "\n",
    "node7 = helper.make_node('Reshape', inputs=['T6', 'shape'], outputs=['T7'])\n",
    "\n",
    "node8 = helper.make_node('Gemm', inputs=['T7', 'W3', 'B3'], outputs=['predictions'])\n",
    "\n",
    "graph = helper.make_graph(\n",
    "    [node1, node2, node3, node4, node5, node6, node7, node8],\n",
    "    'mnist_conv',\n",
    "    [helper.make_tensor_value_info('X', TensorProto.FLOAT, ([batch_size, 1, 28, 28])),\n",
    "     helper.make_tensor_value_info('W1', TensorProto.FLOAT, W1_dims),\n",
    "     helper.make_tensor_value_info('W2', TensorProto.FLOAT, W2_dims),\n",
    "     helper.make_tensor_value_info('W3', TensorProto.FLOAT, W3_dims),\n",
    "     helper.make_tensor_value_info('B1', TensorProto.FLOAT, B1_dims),\n",
    "     helper.make_tensor_value_info('B2', TensorProto.FLOAT, B2_dims),\n",
    "     helper.make_tensor_value_info('B3', TensorProto.FLOAT, B3_dims),\n",
    "     helper.make_tensor_value_info('shape', TensorProto.INT64, [2]),\n",
    "    ],\n",
    "    [helper.make_tensor_value_info('predictions', TensorProto.FLOAT, ([batch_size, 10]))],\n",
    "    [W1, W2, W3, B1, B2, B3, shape]\n",
    ")\n",
    "original_model = helper.make_model(graph, producer_name='onnx-examples')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "onnx.checker.check_model(original_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "inferred_model = shape_inference.infer_shapes(original_model)\n",
    "onnx.save_model(inferred_model, \"mnist_conv_batch_unknown.onnx\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inferencing session"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnxruntime as lotus\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = lotus.InferenceSession('mnist_conv_batch.onnx', None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.00177374 -0.00565182 -0.00091211 -0.00833805 -0.00262394  0.00868058\n",
      "  -0.00174895 -0.00810127  0.01124816  0.01306908]\n",
      " [ 0.00312558 -0.001757   -0.00442985 -0.00995069 -0.00409109  0.00804279\n",
      "  -0.00279926 -0.00883552  0.01240066  0.01041252]\n",
      " [ 0.00396657 -0.00412453 -0.00415219 -0.01012361 -0.00570025  0.00737222\n",
      "  -0.00099745 -0.00989306  0.01327983  0.0105867 ]\n",
      " [ 0.00241887 -0.00515954 -0.00304933 -0.01251889 -0.00433843  0.0081604\n",
      "  -0.00310066 -0.00968494  0.00971858  0.01077508]]\n"
     ]
    }
   ],
   "source": [
    "X_dims = [4, 1, 28, 28]\n",
    "\n",
    "data = np.random.uniform(size=X_dims).astype(np.float32)\n",
    "\n",
    "result = sess.run(['predictions'], {'X': data})\n",
    "\n",
    "print(result[0])\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
